'use client';

import { MDXComponents } from 'mdx/types';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Separator } from '@/components/ui/separator';
import { Copy, Check, ExternalLink } from 'lucide-react';
import { useState } from 'react';

/**
 * 代码复制组件
 * 提供代码块的复制功能
 */
function CodeBlock({
  children,
  className,
  ...props
}: React.HTMLAttributes<HTMLPreElement> & { children?: React.ReactNode }) {
  const [copied, setCopied] = useState(false);

  const copyToClipboard = async () => {
    let text = '';
    if (typeof children === 'string') {
      text = children;
    } else if (
      children &&
      typeof children === 'object' &&
      'props' in children
    ) {
      text = (children as { props: { children: string } }).props.children || '';
    }
    await navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="relative group">
      <pre className={cn('relative overflow-x-auto', className)} {...props}>
        {children}
      </pre>
      <Button
        size="sm"
        variant="ghost"
        className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
        onClick={copyToClipboard}
      >
        {copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
      </Button>
    </div>
  );
}

/**
 * 自定义链接组件
 * 为外部链接添加图标
 */
function CustomLink({
  href,
  children,
  ...props
}: React.AnchorHTMLAttributes<HTMLAnchorElement> & {
  href?: string;
  children?: React.ReactNode;
}) {
  const isExternal = href?.startsWith('http');

  return (
    <a
      href={href}
      className={cn(
        'text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300',
        'inline-flex items-center gap-1 underline underline-offset-4'
      )}
      target={isExternal ? '_blank' : undefined}
      rel={isExternal ? 'noopener noreferrer' : undefined}
      {...props}
    >
      {children}
      {isExternal && <ExternalLink className="h-3 w-3" />}
    </a>
  );
}

/**
 * 自定义表格组件
 * 提供响应式表格样式
 */
function CustomTable({
  children,
  ...props
}: React.TableHTMLAttributes<HTMLTableElement> & {
  children?: React.ReactNode;
}) {
  return (
    <div className="overflow-x-auto">
      <table
        className="w-full border-collapse border border-gray-300 dark:border-gray-700"
        {...props}
      >
        {children}
      </table>
    </div>
  );
}

/**
 * MDX组件映射
 * 定义MDX中各种元素的自定义组件
 */
export const mdxComponents: MDXComponents = {
  // 标题组件
  h1: ({ children, ...props }) => (
    <h1
      className="text-4xl font-bold mb-6 text-gray-900 dark:text-gray-100"
      {...props}
    >
      {children}
    </h1>
  ),
  h2: ({ children, ...props }) => (
    <h2
      className="text-3xl font-semibold mb-4 mt-8 text-gray-900 dark:text-gray-100"
      {...props}
    >
      {children}
    </h2>
  ),
  h3: ({ children, ...props }) => (
    <h3
      className="text-2xl font-semibold mb-3 mt-6 text-gray-900 dark:text-gray-100"
      {...props}
    >
      {children}
    </h3>
  ),
  h4: ({ children, ...props }) => (
    <h4
      className="text-xl font-semibold mb-2 mt-4 text-gray-900 dark:text-gray-100"
      {...props}
    >
      {children}
    </h4>
  ),

  // 段落和文本
  p: ({ children, ...props }) => (
    <p
      className="mb-4 text-gray-700 dark:text-gray-300 leading-relaxed"
      {...props}
    >
      {children}
    </p>
  ),

  // 列表
  ul: ({ children, ...props }) => (
    <ul
      className="mb-4 ml-6 list-disc text-gray-700 dark:text-gray-300"
      {...props}
    >
      {children}
    </ul>
  ),
  ol: ({ children, ...props }) => (
    <ol
      className="mb-4 ml-6 list-decimal text-gray-700 dark:text-gray-300"
      {...props}
    >
      {children}
    </ol>
  ),
  li: ({ children, ...props }) => (
    <li className="mb-1" {...props}>
      {children}
    </li>
  ),

  // 代码
  code: ({ children, className, ...props }) => {
    const isInline = !className;

    if (isInline) {
      return (
        <code
          className="px-1.5 py-0.5 bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-200 rounded text-sm font-mono"
          {...props}
        >
          {children}
        </code>
      );
    }

    return (
      <code className={className} {...props}>
        {children}
      </code>
    );
  },

  pre: CodeBlock,

  // 链接
  a: CustomLink,

  // 表格
  table: CustomTable,
  th: ({ children, ...props }) => (
    <th
      className="border border-gray-300 dark:border-gray-700 px-4 py-2 bg-gray-50 dark:bg-gray-800 font-semibold text-left"
      {...props}
    >
      {children}
    </th>
  ),
  td: ({ children, ...props }) => (
    <td
      className="border border-gray-300 dark:border-gray-700 px-4 py-2"
      {...props}
    >
      {children}
    </td>
  ),

  // 引用
  blockquote: ({ children, ...props }) => (
    <blockquote
      className="border-l-4 border-blue-500 pl-4 my-4 italic text-gray-600 dark:text-gray-400"
      {...props}
    >
      {children}
    </blockquote>
  ),

  // 分隔线
  hr: () => <Separator className="my-8" />,

  // 自定义组件
  Button: Button,
  Badge: Badge,
  Alert: Alert,
  AlertDescription: AlertDescription,
  AlertTitle: AlertTitle,
};

export default mdxComponents;
